package com.lindroy.androidplayer.logic.network2

import com.lindroy.androidplayer.logic.model.ArticleResp
import com.lindroy.androidplayer.logic.model.HttpResult
import com.lindroy.androidplayer.logic.model.LoginResp
import com.lindroy.androidplayer.logic.model.bean.PageDataModel
import com.lindroy.lib_utils.extensions.shortToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext

/**
 * @author Lin
 * @date 2021/4/15
 * @function  处理协程的请求类
 */

object HttpRequestManager {
    /**
     * 注册并登陆
     */
    suspend fun register(username: String, password: String): HttpResult<LoginResp> {
        val registerResult = apiService.register(username, password, password)
        //判断注册结果 注册成功，调用登录接口
        if (registerResult.success) {
            return apiService.login(username, password)
        } else {
            shortToast(registerResult.errorMsg)
            //抛出错误异常
            throw AppException(registerResult.errorCode, registerResult.errorMsg)
        }
    }

    /**
     * 获取首页文章数据
     */
    suspend fun getHomeArticles(pageNo: Int): HttpResult<PageDataModel<ArrayList<ArticleResp>>> =
        withContext(Dispatchers.IO) {
            val articleList = async { apiService.getArticles(pageNo) }
            if (pageNo == 0) {
                val topArticles = async { apiService.getTopArticles() }
                articleList.await().apply { data.datas.addAll(0, topArticles.await().data) }
            } else {
                articleList.await()
            }
        }

}
